var express = require('express');
var router = express.Router();
var path = require("path");
//引入数据模型模块
var user = require("../views/userSchema");

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

router.get('/login', function(req, res, next) {
    res.sendFile(path.join(__dirname, '../views/login.html'));
});

router.get('/addd', (req, res) => {
    res.setHeader('Content-Type', 'application/json;charset=utf-8');
    user.findOne(req.query, (err, data) => {
        if (err) throw err;
        if (data) return res.send(data + "登录成功");

        res.send("登录失败");
    })
})

router.post('/add', (req, res) => {
    res.setHeader('Content-Type', 'application/json;charset=utf-8');
    user.findOne(req.body, (err, data) => {
        if (err) throw err;
        if (data) return res.send(data + "登录成功");

        res.send("登录失败");
    })
})

router.get('/list', (req, res) => {
    user.find((err, result) => {
        //console.log(result)
        // {layout:false}
        res.render('users', { userlist: result });
    })

})

router.post('/adduser', (req, res) => {
    user.create(req.body, (err, result) => {
        if (err) throw err
            //重新查找 展示在页面上
        user.find((err, result) => {
            if (err) throw err
            res.render('users', { userlist: result });
        })
    })
})
router.post('/delete', (req, res) => {
    user.deleteOne(req.body, (err, result) => {
        if (err) throw err
        user.find((err, result) => {
            if (err) throw err
            res.render('users', { userlist: result });
        })
    })
})

//mongo 客户端打开
//show dbs
// use mydb
//


module.exports = router;